package controllers

import (
	"path"
	"time"
	"strconv"
	"strings"

	"github.com/astaxie/beego/orm"

	"read.com/admin/libs"
	"read.com/admin/models"
)

type BookController struct {
	BaseController
}

func (self *BookController) List() {
	total := models.GetTotal()
	self.Data["catList"], _ = models.GetAllSysCat()
	self.Data["pageTitle"] = "书籍管理"
	self.Data["totalNum"] = total["totalNum"]
	self.Data["totalSign"] = total["totalSign"]
	self.Data["totalUnSign"] = total["totalUnSign"]
	self.Data["maleNum"] = total["maleNum"]
	self.Data["femaleNum"] = total["femaleNum"]
	self.display()
}

func (self *BookController) Detail() {
	id, _ := self.GetInt("id")
	book := models.GetBookByID(id)
	cats := models.GetCatByChannel(book.ChannelType)
	tags := models.GetTagsById(book.Tags)
	ossPath := models.GetCatById(book.Category).OssPath
	self.Data["onlineChapter"] = strconv.Itoa(book.ReleaseChapterTotal())
	self.Data["pageTitle"] = "书籍编辑 ---- " + book.Name
	self.Data["book"] = book
	self.Data["finishTime"] = book.ChapterFinishTime.Format("2006-01-02 15:04:05")
	self.Data["tags"] = tags
	self.Data["cats"] = cats
	self.Data["ossPath"] = ossPath
	self.Data["createTime"] = book.CreateTime.Format("2006-01-02 15:04:05")
	self.Data["releaseTime"] = strings.Split(book.ReleaseTime.Format("2006-01-02 15:04:05"), " ")[0] + " " + book.ChapterTime.Format("15:04:05")
	self.display()
}

func (self *BookController) Chapter() {
	id, _ := self.GetInt("id")
	ossPath := models.GetCatById(models.GetBookByID(id).Category).OssPath
	total, _ := self.GetInt("total")
	online, _ := self.GetInt("online")
	self.Data["pageTitle"] = "章节设置 ---- " + self.GetString("name")
	self.Data["id"] = id
	self.Data["ossPath"] = ossPath
	self.Data["bookSerialId"] = models.GetBookByID(id).SerialId
	self.Data["total"] = total
	self.Data["online"] = online
	self.Data["rest"] = total - online
	self.Data["words"] = self.GetString("words")
	self.Data["chapterPriceSum"] = self.GetString("chapterPriceSum")
	self.display()
}

func (self *BookController) Chaptertable() {
	bookId, _ := self.GetInt("bookId")
	cond := orm.NewCondition()
	cond = cond.And("book_id", bookId)

	//列表参数
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 10
	}
	// 章节名称
	name := self.GetString("name")
	if name != "" {
		cond = cond.And("name__icontains", name)
	}

	result, count,tableHead := models.GetChapterList(page, limit, cond)
	export := self.GetString("export")
	if export == "1" { // 导出excel格式
		libs.FormatExcel(self.Ctx.Output, result,tableHead)
	} else { // 查询
		self.ajaxList("成功", MSG_OK, count, result)
	}
}

func (self *BookController) Table() {
	cond := orm.NewCondition()

	//列表参数
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 10
	}
	// 频道
	channel := self.GetString("channel")
	if channel != "" {
		if channel != "-1" {
			cond = cond.And("channel_type", channel)
		}
	}

	// 分类
	cat := self.GetString("cat")
	if cat != "" {
		if cat != "-1" {
			cond = cond.And("category", cat)
		}
	}

	// 来源
	isSign := self.GetString("isSign")
	if isSign != "" {
		if isSign != "-1" {
			cond = cond.And("is_sign", isSign)
		}
	}

	// 判断是书名还是作者名
	value := self.GetString("value")
	if value != "" {
		filed := strings.Split(value, "-")[0]
		filedValue := strings.Split(value, "-")[1]
		if filed == "0" && filedValue != "" {
			cond = cond.And("name__icontains", filedValue)
		} else if filed == "1" && filedValue != "" {
			cond = cond.And("author__icontains", filedValue)
		}
	}

	// 状态
	status := self.GetString("status")
	if status != "-1" {
		now := time.Now().Format("2006-01-02 15:04:05")
		switch status {
		case "0": // 更新中
			cond1 := orm.NewCondition().And("status", 0).Or("chapter_finish_time__gte", now)
			cond = cond.And("release_time__lt", now).AndCond(cond1)
		case "1": // 已完结
			cond1 := orm.NewCondition().And("status", 1).And("chapter_finish_time__lt", now)
			cond = cond.And("release_time__lt", now).AndCond(cond1)
		case "2": // 未上架
			cond = cond.And("release_time__gte", now)
		}
	}

	// 是查询还是导出
	result, count, tableHead := models.GetBookList(page, limit, cond)
	export := self.GetString("export")
	if export == "1" { // 导出excel格式
		libs.FormatExcel(self.Ctx.Output, result,tableHead)
	} else { // 查询
		self.ajaxList("成功", MSG_OK, count, result)
	}
}

func (self *BookController) SetClicks() {
	id, _ := self.GetInt("id")
	clicks, _ := self.GetInt64("clicks")
	_, err := models.UpdateClicks(id, clicks)
	if err != nil {
		self.ajaxMsg("更新失败", MSG_ERR)
	} else {
		self.ajaxMsg("更新成功", MSG_OK)
	}
}

func (self *BookController) GetCats() {
	channel, _ := self.GetInt("chanel")
	cats := models.GetCatByChannel(int8(channel))
	self.ajaxList("成功", MSG_OK, int64(len(cats)), cats)
}

func (self *BookController) SetPrice() {
	bookId,_ := self.GetInt("bookId")
	ids := self.GetString("ids")
	price, _ := self.GetInt("price")
	_, err := models.UpdatePriceById(ids, price,bookId)
	if err != nil {
		self.ajaxMsg("更新失败", MSG_ERR)
	} else {
		self.ajaxMsg("更新成功", MSG_OK)
	}
}


func (self *BookController) SetBookPrice() {
	bookId,_ := self.GetInt("bookId")
	price, _ := self.GetInt("price")
	 err := models.UpdateBookPriceById(bookId, price)
	if err != nil {
		self.ajaxMsg("更新失败", MSG_ERR)
	} else {
		self.ajaxMsg("更新成功", MSG_OK)
	}
}


func (self *BookController) SetBook() {
	id, _ := self.GetInt("id")
	channel, _ := self.GetInt8("channel")
	cat, _ := self.GetInt("cat")
	isSign, _ := self.GetInt8("isSign")
	chapterStart, _ := self.GetInt("chapterStart")
	chapterDaily, _ := self.GetInt16("chapterDaily")
	clicks, _ := self.GetInt64("clicks")
	tag := self.GetString("tag")
	tagArr := strings.Split(tag, ",")
	tag = models.GetTagByName(tagArr)

	book := models.GetBookByID(id)
	book.Name = self.GetString("name")
	book.Author = self.GetString("author")
	book.ChannelType = channel
	book.Category = cat
	book.Tags = tag
	book.IsSign = isSign
	book.Desc = self.GetString("desc")
	book.Tip = self.GetString("tip")
	book.ReleaseTime = libs.StrToTime(self.GetString("releaseTime"))
	book.ChapterStart = chapterStart
	book.ChapterDaily = chapterDaily
	book.ChapterFinishTime = libs.StrToTime(self.GetString("finishTime"))
	book.Clicks = clicks
	ok := models.UpdateBook(book)
	if ok {
		self.ajaxMsg("更新成功", MSG_OK)
	} else {
		self.ajaxMsg("更新失败", MSG_ERR)
	}
}

func (self *BookController) GetBook() {
	id, _ := self.GetInt("id")
	channel, _ := self.GetInt8("channel")
	book := models.GetBookByIdAndChannel(id, channel)
	self.ajaxList("成功", MSG_OK, 1, book)
}

func (self *BookController) UpLoadImage() {
	id, _ := self.GetInt("id")
	name := self.GetString("name")
	file, fileHeader, _ := self.GetFile("file")

	if name != "cover" && name != "poster" {
		self.ajaxMsg("参数name无权限", MSG_ERR)
		return
	}
	if ext := path.Ext(fileHeader.Filename); ext != ".jpg" && ext != ".jpeg" {
		self.ajaxMsg("请上传JPG图片", MSG_ERR)
		return
	}

	book := models.GetBookByID(id)
	cat := models.GetCatById(book.Category)

	// 上传图片到OSS:(key=cat+SerialId+cover),如CYCS00/00C55AC4551D7723BD0E83EC2950E47F/cover.jpg
	ossKey := cat.OssPath + "/" + book.SerialId + "/" + name + ".jpg"
	ok := libs.NewAliyunOss().UploadImage(ossKey, file)
	if ok {
		self.ajaxMsg(ossKey, MSG_OK)
	} else {
		self.ajaxMsg("更新失败", MSG_ERR)
	}
}
